<template>
  <view>
    <!-- 顶部导航 -->
    <lg-topbar bgColor="#127B56" height="192rpx">
      <view class="bg-topbar-content">
        <view>Cart</view>
        <view style="width: 100%; height: 70rpx; margin-top: 20rpx">
          <uv-tabs
            :list="tabList"
            :current="currentTab"
            @click="tabClick"
            @change="tabChange"
            :scrollable="tabList.length > 5 ? true : false"
            itemStyle="color:#fff; height: 70rpx;"
            lineColor="#fff"
            :activeStyle="{
              color: '#fff',
              fontWeight: 'bold',
              transform: 'scale(1.05)',
            }"
            :inactiveStyle="{
              color: '#fff',
              transform: 'scale(1)',
            }"
          ></uv-tabs>
        </view>
      </view>
    </lg-topbar>
    <view class="cart-content">
      <view v-if="cartList?.length > 0">
        <cart-item
          v-for="item in cartList"
          :key="item.id"
          :item="item"
          @delete="handleDeleteItem"
        />
      </view>
      <BgEmpty v-if="showEmpty" />
    </view>
    <bottom-bar v-if="!showEmpty">
      <view class="custom-bottom">
        <view class="left">
          <view class="total-price">
            <text
              >{{ cartList.length }} items, VAT:
              {{ total.vat ?? "0" }} SAR</text
            >
          </view>
          <view class="selected-info"
            >Total: {{ total.totalAmount ?? "0" }} SAR</view
          >
        </view>
        <view class="Confrm" @click="onCheckout">
          {{ t("Check out")
          }}<uv-icon class="flip" name="arrow-right" color="#fff"></uv-icon>
        </view>
      </view>
    </bottom-bar>
    <AddressModel
      ref="addressModelRef"
      class="address-model"
      @confirm="onConfirm"
    />
    <shopCartPlace ref="cartPlaceRef" />
    <uv-modal ref="miniModalRef" @confirm="confirm" width="390rpx">
      <template #default>
        <view
          style="
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 24rpx;
            color: #898989;
          "
        >
          <view>
            <image
              style="width: 90rpx; height: 90rpx"
              src="@/static/images/cart/err.png"
              mode="widthFix"
            ></image>
          </view>
          <view style="text-align: center">{{
            t("Minimum order amount:")
          }}</view>
          <view style="text-align: center">{{ t("10,000 SAR") }}</view>
        </view>
      </template>
      <template #confirmButton>
        <view class="confirm-btn">
          <view class="confirm-btn-text" @click="miniModalRef.close()">{{
            t("OK")
          }}</view>
        </view>
      </template>
    </uv-modal>
  </view>
</template>
<script setup>
import bottomBar from "@/components/BgBottom/index.vue";
import cartItem from "./components/cart-item.vue";
import AddressModel from "@/components/AddressModel/index.vue";
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import BgEmpty from "@/components/BgEmpty";
import { useDeviceStore } from "@/store";
import { CartAPI, OrderAPI } from "@/api";
import { onShow } from "@dcloudio/uni-app";
import shopCartPlace from "@/components/shopCartView/shopCartPlace.vue";
const device = useDeviceStore();
const { t } = useI18n();
const miniModalRef = ref(null);
const addressModelRef = ref(null);
const cartPlaceRef = ref(null);
const total = ref({});
const showEmpty = ref(false);
const currentTab = ref(0);
const cartList = ref([]);
const cartData = ref({});
const tabList = ref([]);
const orderDetailList = ref([]);
const queryMyCart = async () => {
  CartAPI.getmyCartList("normal", device.MyShop.id, {
    shopId: device.MyShop.id,
  }).then((res) => {
    if (res.code == 200 && res.data) {
      cartData.value = res.data;
      tabList.value = Object.keys(res.data).map((item) => ({
        name: item,
      }));
      cartList.value = res.data[tabList.value[currentTab.value]?.name];
      if (cartList.value?.length > 0) {
        showEmpty.value = false;
        getTotal();
      } else {
        showEmpty.value = true;
      }
    } else {
      tabList.value = [];
      cartList.value = [];
      showEmpty.value = true;
    }
  });
};
const getTotal = () => {
  const data = JSON.parse(JSON.stringify(cartList.value)).map((item) => {
    return {
      oe: item.oe,
      quantity: item.quantity,
    };
  });
  orderDetailList.value = data;
  CartAPI.getCartTotal(device.MyShop.id, data).then((res) => {
    console.log(res);
    if (res?.data) {
      total.value = res.data;
    }
  });
};

onShow(() => {
  queryMyCart();
});
const tabChange = (index) => {
  currentTab.value = index.index;
};
const tabClick = (index) => {
  cartList.value = cartData.value[index.name];
  if (cartList.value.length > 0) {
    showEmpty.value = false;
    getTotal();
  } else {
    showEmpty.value = true;
  }
};
//删除购物车商品
function handleDeleteItem(item) {
  CartAPI.deleteCart(
    {
      shopId: device.MyShop.id,
      carMakeId: item.id,
      oeList: [item.oe],
      quantity: item.quantity,
    },
    "normal"
  ).then((res) => {
    console.log(res);
    if (res.code == 200) {
      queryMyCart();
    }
  });
}

function onCheckout() {
  if (total.value.totalAmount > 1000) {
    addressModelRef.value.open();
  } else {
    miniModalRef.value.open();
    // uni.showToast({
    //   title: '订单金额必须大于1000 SAR',
    //   icon: 'none'
    // })
  }
}
async function onConfirm(addressInfo) {
  addressModelRef.value.close();
  orderDetailList;
  let res = await OrderAPI.postPlaceOrder({
    shopId: device.MyShop.id,
    paymentMethod: device.MyShop.paymentMethod, // 0现结 1账期
    orderType: "0", //0->正常订单；1->促销订单
    remark: addressInfo.note, //备注
    orderDetailList: orderDetailList.value,
    orderReceiverAddressDto: {
      receiverName: addressInfo.name, //收货人姓名
      receiverPhone: addressInfo.phone, //收货人电话
      // "receiverProvince": "省份/直辖市", //省份/直辖市
      // "receiverCity": "城市", //城市
      // "receiverRegion": "区", //区
      receiverDetailAddress: addressInfo.address, //详细地址
    },
  });
  console.log(res);
  // cartPlaceRef.value.control(true)
  uni.navigateTo({
    url: "/pages/cart/cartSuccess",
  });
}
</script>
<style lang="scss" scoped>
@import "@/static/css/index.scss";

.bg-topbar-content {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  // word-break: break-all;
  color: $primary-f;
  overflow: hidden;
}

.cart-tabs {
  background-color: $primary-b;
  height: 60rpx;
}

.cart-content {
  margin: 20rpx;
  width: calc(100vw - 40rpx);
  height: calc(100vh - 252rpx);
  background-color: #fff;
  border-radius: 6rpx;
}

.cart-item-content {
  display: flex;
  padding: 15px;
  align-items: center;

  .item-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    margin-right: 12px;
  }

  .item-info {
    flex: 1;

    .item-name {
      font-size: 16px;
      color: #333;
      margin-bottom: 8px;
    }

    .item-price {
      font-size: 18px;
      color: #ff3b30;
      font-weight: bold;
    }
  }
}

.custom-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #fff;

  .left {
    .total-price {
      font-size: 14px;
      color: #9cc8b8;

      .price {
        font-size: 20px;
        font-weight: bold;
      }
    }

    .selected-info {
      font-size: 12px;
      margin-top: 4px;
    }
  }

  .right {
    :deep(.uv-button) {
      min-width: 120px;
    }
  }
}

.Confrm {
  display: flex;
  align-items: center;
}

.address-model {
  z-index: 99999;
}

.confirm-btn {
  display: flex;
  justify-content: center;
  color: #fff;
  font-size: 32rpx;
  width: 100%;
  margin-bottom: 20rpx;

  .confirm-btn-text {
    display: flex;
    background-color: #1aad19;
    width: 200rpx;
    height: 80rpx;
    align-items: center;
    justify-content: center;
    border-radius: 8rpx;
  }
}
</style>
